package com.sky.task;

import ch.qos.logback.classic.spi.LoggerContextAware;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ?")//每分钟触发一次
    public void processTimeOutOrder(){
        log.info("处理超时订单{}", LocalDateTime.now());

        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);//当前时间-15分钟
        //select * from orders where status = ? and order_time <(当前时间-15分钟)
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);

        //更新订单数据
        if(ordersList.size()>0 && ordersList != null){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);//取消订单
                orders.setCancelTime(LocalDateTime.now());//取消时间
                orders.setCancelReason("订单超时，自动取消");//取消原因
                orderMapper.update(orders);
            }
        }

    }

    /**
     * 处理一直处于派送中的订单（商家没有及时点完成）
     */
    @Scheduled(cron = "0 0 1 * * ?")//每天凌晨一点触发检查
    public void processDeliveryOrder(){
        log.info("处理一直处于派送中的订单{}",LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);//当前时间一小时前 上一个工作日
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, time);

        //更新订单数据
        if(ordersList.size()>0 && ordersList != null){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);//完成订单
                orderMapper.update(orders);
            }
        }
    }
}
